package org.jeecg.modules.bus.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.annotation.ApiLogin;
import org.jeecg.com.util.ThirdSessionHolder;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TenantContextHolder;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.config.ApiVersion;
import org.jeecg.config.ApiVersionConstant;
import org.jeecg.config.WebConfig;
import org.jeecg.modules.business.dto.UserGroupDto;
import org.jeecg.modules.business.dto.UserLabelDto;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.*;
import org.jeecg.modules.business.vo.MemberCardStatVo;
import org.jeecg.modules.mall.entity.MallUserInfo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wxuser.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 会员卡
 * @Author: jeecg-boot
 */
@Api(tags="会员卡")
@RestController
@RequestMapping("/mall-api/member-card")
@Slf4j
public class MemberCardController extends WebConfig {
	@Resource
	private IBusMemberCardService busMemberCardService;
	 @Resource
	 private IBusHotelService busHotelService;
	 @Resource
	 private IBusMarketMemberService busMarketMemberService;
	 @Resource
	 private IBusMarketMemberGroupService busMarketMemberGroupService;
	 @Resource
	 private IBusMarketMemberLableService busMarketMemberLableService;
	@Resource
	private IUserInfoService userInfoService;
	@Resource
	private IBusMemberBalanceLogService busMemberBalanceLogService;
	@Resource
	private IBusMemberPointLogService busMemberPointLogService;
	@Resource
	private IBusMarketRechargeService busMarketRechargeService;
	@Resource
	private ISysBaseAPI sysBaseAPI;
	@Resource
	private ISysUserService sysUserService;
	/**
	 * 用户购买的会员卡分页列表查询
	 *
	 * @param busMemberCard
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="用户购买的会员卡分页列表查询", notes="用户购买的会员卡分页列表查询")
	@GetMapping(value = "/list")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<IPage<BusMemberCard>> queryPageList(BusMemberCard busMemberCard,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String tenantId = TenantContextHolder.getTenantId();
		String userId = ThirdSessionHolder.getUserId();
		LambdaQueryWrapper<BusMemberCard> queryWrapper = QueryGenerator.initQueryWrapper(busMemberCard, req.getParameterMap()).lambda();
		MallUserInfo mallUserInfo = userInfoService.getById(userId);
		queryWrapper.and(t -> {
			t.eq(BusMemberCard::getUserId, userId);
			t.or().eq(BusMemberCard::getMobile, mallUserInfo.getMobile());
		});
		queryWrapper.eq(BusMemberCard::getTenantId,tenantId);
		Page<BusMemberCard> page = new Page<BusMemberCard>(pageNo, pageSize);
		IPage<BusMemberCard> pageList = busMemberCardService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			BusHotel hotle = busHotelService.getById(item.getHotelId());
			if (hotle != null) {
				item.setHotelName(hotle.getName());
			}
			BusMarketMember busMarketMember = busMarketMemberService.getById(item.getGradeId());
			if (busMarketMember != null) {
				item.setMarketMember(busMarketMember);
			}
			if (ObjectUtils.isNotEmpty(item.getGroupId())) {
				BusMarketMemberGroup busMarketMemberGroup = busMarketMemberGroupService.getById(item.getGroupId());
				if (busMarketMemberGroup != null) {
					item.setGroupName(busMarketMemberGroup.getName());
				}
			}
			if (ObjectUtils.isNotEmpty(item.getLabelId())) {
				BusMarketMemberLable busMarketMemberLable = busMarketMemberLableService.getById(item.getLabelId());
				if (busMarketMemberLable != null) {
					item.setLabelName(busMarketMemberLable.getName());
				}
			}
		});
		return Result.OK(pageList);
	}



	/**
	 *   添加会员卡
	 *
	 * @param busMemberCard
	 * @return
	 */
	@AutoLog(value = "添加会员卡")
	@ApiOperation(value="添加会员卡", notes="添加会员卡")
	@PostMapping(value = "/add")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<String> add(@RequestBody BusMemberCard busMemberCard) {
		String tenantId = TenantContextHolder.getTenantId();
		String userId = ThirdSessionHolder.getUserId();
		BusMarketMember busMarketMember = busMarketMemberService.getById(busMemberCard.getGradeId());
		if (busMarketMember == null) {
			return Result.error("会员卡不存在！");
		}
		if (!busMarketMember.getHotelId().equals(busMemberCard.getHotelId())) {
			return Result.error("会员卡不存在！");
		}
		MallUserInfo mallUserInfo = userInfoService.getById(userId);
		LambdaQueryWrapper<BusMemberCard> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BusMemberCard::getTenantId, tenantId);
		queryWrapper.and(t -> {
			t.eq(BusMemberCard::getUserId, userId);
			t.or().eq(BusMemberCard::getMobile, mallUserInfo.getMobile());
		});
		queryWrapper.eq(BusMemberCard::getHotelId, busMemberCard.getHotelId()).orderByDesc(BusMemberCard::getCreateTime).last("limit 1");
		BusMemberCard card = busMemberCardService.getOne(queryWrapper);
		if (card != null) {
			BusMarketMember member = busMarketMemberService.getById(card.getGradeId());
			if (member != null) {
				if (member.getLevel() > busMarketMember.getLevel()) {
					return Result.error("会员卡不能降级！");
				}
				card.setGradeId(busMemberCard.getGradeId());
				busMemberCardService.updateById(card);
				return Result.OK("升级成功！");
			}
		}
		busMemberCard.setTenantId(tenantId);
		busMemberCard.setUserId(userId);
		busMemberCardService.save(busMemberCard);

		//创建业务消息信息
		LambdaQueryWrapper<SysUser> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
		lambdaQueryWrapper3.eq(SysUser::getDelFlag, 0);
		lambdaQueryWrapper3.eq(SysUser::getRelTenantIds, busMemberCard.getTenantId());
		List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper3);
		String userIds = "";
		for (SysUser sysUser : sysUsers) {
			userIds += sysUser.getUsername() + ",";
		}
		if (userIds.length() > 0) {
			MessageDTO messageDTO = new MessageDTO();
			messageDTO.setFromUser("");
			messageDTO.setToUser(userIds);
			messageDTO.setTitle("用户购买了会员卡");
			messageDTO.setContent("用户购买了会员卡");
			messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
			sysBaseAPI.sendSysAnnouncement(messageDTO);
		}
		return Result.OK("添加成功！");
	}


	/**
	 * 会员卡类型列表
	 * @param busMarketMember
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "会员卡类型列表")
	@ApiOperation(value="会员卡类型列表", notes="会员卡类型列表")
	@PostMapping(value = "/member-card-type-list")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<IPage<BusMarketMember>> getMemberCardTypeList(BusMarketMember busMarketMember,
													  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  HttpServletRequest req) {
		String tenantId = TenantContextHolder.getTenantId();
		LambdaQueryWrapper<BusMarketMember> queryWrapper = QueryGenerator.initQueryWrapper(busMarketMember, req.getParameterMap()).lambda();
		queryWrapper.eq(BusMarketMember::getTenantId,tenantId);
		Page<BusMarketMember> page = new Page<BusMarketMember>(pageNo, pageSize);
		IPage<BusMarketMember> pageList = busMarketMemberService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 根据卡片获取对应会员卡余额消费明细列表
	 * @param busMemberBalanceLog
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "根据卡片获取对应会员卡余额消费明细列表")
	@ApiOperation(value="根据卡片获取对应会员卡余额消费明细列表", notes="根据卡片获取对应会员卡余额消费明细列表")
	@PostMapping(value = "/member-card-balance-log-list")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<IPage<BusMemberBalanceLog>> getMemberCardBalanceLogList(BusMemberBalanceLog busMemberBalanceLog,
																@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																HttpServletRequest req) {
		if(StringUtils.isBlank(busMemberBalanceLog.getMemberId())){
			return Result.error("缺少会员id");
		}
		String tenantId = TenantContextHolder.getTenantId();
		LambdaQueryWrapper<BusMemberBalanceLog> queryWrapper = QueryGenerator.initQueryWrapper(busMemberBalanceLog, req.getParameterMap()).lambda();
		queryWrapper.eq(BusMemberBalanceLog::getTenantId,tenantId);
		Page<BusMemberBalanceLog> page = new Page<BusMemberBalanceLog>(pageNo, pageSize);
		IPage<BusMemberBalanceLog> pageList = busMemberBalanceLogService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@AutoLog(value = "根据卡片获取对应会员卡积分消费明细列表")
	@ApiOperation(value="根据卡片获取对应会员卡积分消费明细列表", notes="根据卡片获取对应会员卡积分消费明细列表")
	@PostMapping(value = "/member-card-point-log-list")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<IPage<BusMemberPointLog>> getMemberCardBalanceLogList(BusMemberPointLog busMemberPointLog,
																		  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																		  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																		  HttpServletRequest req) {
		if(StringUtils.isBlank(busMemberPointLog.getMemberId())){
			return Result.error("缺少会员id");
		}
		String tenantId = TenantContextHolder.getTenantId();
		LambdaQueryWrapper<BusMemberPointLog> queryWrapper = QueryGenerator.initQueryWrapper(busMemberPointLog, req.getParameterMap()).lambda();
		queryWrapper.eq(BusMemberPointLog::getTenantId,tenantId);
		Page<BusMemberPointLog> page = new Page<BusMemberPointLog>(pageNo, pageSize);
		IPage<BusMemberPointLog> pageList = busMemberPointLogService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 获取充值金额选项列表
	 * @param busMarketRecharge
	 * @param req
	 * @return
	 */
	@AutoLog(value = "获取充值金额选项列表")
	@ApiOperation(value="获取充值金额选项列表", notes="获取充值金额选项列表")
	@PostMapping(value = "/market-recharge-list")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<List<BusMarketRecharge>> getMarketRechargeList(BusMarketRecharge busMarketRecharge,HttpServletRequest req) {
		String tenantId = TenantContextHolder.getTenantId();
		LambdaQueryWrapper<BusMarketRecharge> queryWrapper = QueryGenerator.initQueryWrapper(busMarketRecharge, req.getParameterMap()).lambda();
		queryWrapper.eq(BusMarketRecharge::getTenantId, tenantId);
		List<BusMarketRecharge> list = busMarketRechargeService.list(queryWrapper);
		return Result.OK(list);
	}

	/**
	 *   会员卡充值余额
	 *
	 * @param busMemberBalanceLog
	 * @return
	 */
	@AutoLog(value = "会员卡充值余额")
	@ApiOperation(value="会员卡充值余额", notes="会员卡充值余额")
	@PostMapping(value = "/member-card-balance-recharge")
	@ApiLogin
	@ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
	public Result<String> balanceRecharge(@RequestBody BusMemberBalanceLog busMemberBalanceLog) {
		String tenantId = TenantContextHolder.getTenantId();
		String userId = ThirdSessionHolder.getUserId();
		busMemberBalanceLog.setType(1);
		busMemberBalanceLog.setPayMoney(busMemberBalanceLog.getMoney());
		busMemberBalanceLog.setPaymentMethod("");
		busMemberBalanceLog.setTenantId(tenantId);
		busMemberBalanceLog.setStatus(0);
		Result result = busMemberBalanceLogService.saveBalance(busMemberBalanceLog);
		if (result.isSuccess()) {
			//创建业务消息信息
			LambdaQueryWrapper<SysUser> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
			lambdaQueryWrapper3.eq(SysUser::getDelFlag, 0);
			lambdaQueryWrapper3.eq(SysUser::getRelTenantIds, busMemberBalanceLog.getTenantId());
			List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper3);
			String userIds = "";
			for (SysUser sysUser : sysUsers) {
				userIds += sysUser.getUsername() + ",";
			}
			if (userIds.length() > 0) {
				MessageDTO messageDTO = new MessageDTO();
				messageDTO.setFromUser("");
				messageDTO.setToUser(userIds);
				messageDTO.setTitle("用户会员卡充值余额");
				messageDTO.setContent("用户会员卡充值余额");
				messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
				sysBaseAPI.sendSysAnnouncement(messageDTO);
			}
		}
		return result;
	}
}
